-- Write a program that reads a text file, 
-- sorts the content of each line in alphabetical order
-- and rewrites the file.

-- case 1: lua rewrite_in_order.lua 				--> stdin to stdout
-- case 2: lua rewrite_in_order.lua f1 			--> f1 to stdout
-- case 3: lua rewrite_in_order.lua f1 f2 	--> f1 to f2

local lines = {}

function rewriteInOrder (src, dest)
	for line in src:lines() do
		lines[#lines + 1] = line
	end
	table.sort(lines)
	for _, line in ipairs(lines) do
		dest:write(line, "\n")
	end
end

function isExist (file)
	local flag = io.open(file, "r")
	if flag == nil then
		return false
	else
		flag:close()
		return true
	end
end

if arg[1] == nil then
	rewriteInOrder(io.stdin, io.stdout)
elseif arg[2] == nil then
	local src = assert(io.open(arg[1], "r"))
	rewriteInOrder(src, io.stdout)
	src:close()
else
	local src = assert(io.open(arg[1], "r"))
	local flag = true
	if isExist(arg[2]) then 
		io.write("Output file <" .. arg[2] .. "> is exist (y->write/n->exit): ")
		local c = io.read(1)
		if c == 'n' then flag = false end
	end
	if flag == true then
		local dest = assert(io.open(arg[2], "w+"))
		rewriteInOrder(src, dest)
		dest:close()
	end
	src:close()
end
